package com.pine.dcts.auth.verfivation;


import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @Description: Redis缓存，会自动过期
 * @Author: xiaoyuan
 * @Date: 2020/6/30 14:37
 */

public class RedisVerificationCodeCache implements VerificationCodeCache {



    private StringRedisTemplate redisTemplate;

    private Long expireIn = 5L * 60L*100L;

    public RedisVerificationCodeCache(StringRedisTemplate redisTemplate){
        this.redisTemplate = redisTemplate;
    }
    public RedisVerificationCodeCache(StringRedisTemplate redisTemplate,Long expireIn){
        this.expireIn = expireIn;
        this.redisTemplate = redisTemplate;
    }



    @Override
    public void set(String cacheName, String key, String value){
        redisTemplate.opsForValue().set(cacheName + ":" + key,value);
        redisTemplate.expire(cacheName + ":" + key,expireIn, TimeUnit.MILLISECONDS);
    }

    @Override
    public void remove(String cacheName, String key) {
        redisTemplate.delete(cacheName + ":" + key);
    }

    @Override
    public String get(String cacheName, String key){
        return redisTemplate.opsForValue().get(cacheName + ":" + key);
    }

    @Override
    public boolean validate(String cacheName, String key, String value){
        String originValue = this.get(cacheName,key);
      //  remove(cacheName,key);
        if(StringUtils.isNotEmpty(originValue)){
            return originValue.equalsIgnoreCase(value);
        }
        return  false;
    }

    @Override
    public boolean isExpire(String cacheName, String key) {
        return redisTemplate.opsForValue().get(cacheName + ":" + key) == null;
    }
}
